﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using TheOutfield.UmbExt.UniversalMediaPicker.Interfaces;
using umbraco.cms.businesslogic.datatype;

namespace TheOutfield.UmbExt.UniversalMediaPicker
{
    public class UniversalMediaPickerPrevalueEditor : AbstractPrevalueEditor
    {
        private UniversalMediaPickerDataType dataType;

        private LiteralControl providersLiteralControl = new LiteralControl();
        private IConfigControl configControl;
        private TextBox cacheDurationTextBox = new TextBox();

        private string currentProviderAlias = "";

        public UniversalMediaPickerPrevalueEditor(UniversalMediaPickerDataType dataType)
        {
            this.dataType = dataType;
            this.dataType.DBType = DBTypes.Nvarchar;
        }

        protected override void CreateChildControls()
        {
            // Update selected provider alias
            if (Page.IsPostBack)
                currentProviderAlias = Page.Request.Form["UniversalMediaPicker_ProvidersDropDownList"];
            else
                currentProviderAlias = dataType.Config.ProviderAlias;

            // Construct provider drop down list
            // NB: We build the control as a literal as we need controls value in OnInit
            // to be able to load the options control
            providersLiteralControl.Text = "<select id='UniversalMediaPicker_ProvidersDropDownList' name='UniversalMediaPicker_ProvidersDropDownList' class='guiInputText guiInputStandardSize' onchange='__doPostBack(this.id, \"\");'>";
            providersLiteralControl.Text += "<option value=''>-- Please select --</option>";

            foreach (var providerKey in UniversalMediaPickerProviderFactory.Providers.Keys)
            {
                providersLiteralControl.Text += "<option value='" + providerKey + "'";

                if (!string.IsNullOrEmpty(currentProviderAlias) && providerKey == currentProviderAlias)
                    providersLiteralControl.Text += " selected='selected'";

                providersLiteralControl.Text += ">" + providerKey + "</option>";
            }

            providersLiteralControl.Text += "</select>";

            // Check for a selected provider 
            if (!string.IsNullOrEmpty(currentProviderAlias))
            {
                var currentProvider = UniversalMediaPickerProviderFactory.CreateProvider(currentProviderAlias,
                    dataType.Config.ProviderAlias == currentProviderAlias ? dataType.Config.ProviderConfig : "");

                configControl = currentProvider.ConfigControl;
                configControl.Control.ID = "UniversalMediaPicker_" + currentProviderAlias + "OptionsControl";

                Controls.Add(configControl.Control);

                cacheDurationTextBox.ID = currentProviderAlias +"CacheDurationTextBox";
                cacheDurationTextBox.CssClass = "guiInputText guiInputStandardSize";
                cacheDurationTextBox.EnableViewState = false;

                Controls.Add(cacheDurationTextBox);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
                cacheDurationTextBox.Text = dataType.Config.ProviderAlias == currentProviderAlias ? dataType.Config.CacheDuration.ToString() : "";

            base.OnLoad(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "universalMediaPicker");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            // add property fields
            writer.AddFormRow("Provider:", "Please select a provider for the media picker", providersLiteralControl);

            if (!string.IsNullOrEmpty(currentProviderAlias))
            {
                configControl.Control.RenderControl(writer);

                writer.AddFormRow("Cache Duration:", "Number of second to cache API calls", cacheDurationTextBox);
            }

            writer.RenderEndTag();
        }

        public override void Save()
        {
            if(Page.IsValid)
            {
                var config = dataType.Config;
                config.ProviderAlias = currentProviderAlias;
                config.CacheDuration = 0;

                if (configControl != null)
                {
                    config.ProviderConfig = configControl.Value;

                    var cacheDuration = 0;
                    if (int.TryParse(cacheDurationTextBox.Text, out cacheDuration))
                        config.CacheDuration = cacheDuration;
                }

                dataType.Config = config;

                UniversalMediaPickerCache.Flush(dataType.DataTypeDefinitionId + "$");
            }
        }
    }
}